package cn.itcast.web.controller.cargo;

import cn.itcast.domain.cargo.*;
import cn.itcast.service.cargo.*;
import cn.itcast.web.controller.BaseController;
import cn.itcast.web.util.FileUploadUtil;
import com.alibaba.dubbo.config.annotation.Reference;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import java.io.InputStream;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @ClassName: InvoiceController
 * @Description: 发票管理
 * @Author LianQiang
 * @Date 2020/11/23
 * @Version 1.0
 */
@Controller
@RequestMapping("/cargo/invoice")
@Slf4j
public class InvoiceController extends BaseController {

    @Reference
    private InvoiceService invoiceService;
    @Reference
    private PackingService packingService;
    @Reference
    private ContractService contractService;
    @Reference
    private ShippingService shippingService;
    @Autowired
    private FileUploadUtil fileUploadUtil;
    @Reference
    private ExportService exportService;

    @RequestMapping("/list")
    public String list(@RequestParam(defaultValue = "1") Integer pageNum,
                       @RequestParam(defaultValue = "5") Integer pageSize) {
        log.info("执行购销合同列表查询开始...");
 /*       InvoiceExample invoiceExample = new InvoiceExample();
        // 获取条件的集合
        InvoiceExample.Criteria criteria = invoiceExample.createCriteria();
        criteria.andCompanyIdEqualTo(getLoginCompanyId());
        invoiceExample.setOrderByClause("invoice_time desc");*/
        InvoiceExample invoiceExample = new InvoiceExample();
        invoiceExample.createCriteria().andCompanyIdEqualTo(getLoginCompanyId());
        invoiceExample.setOrderByClause("invoice_time desc");
        PageInfo<Invoice> pageInfo = invoiceService.findByPage(invoiceExample, pageNum, pageSize);
        request.setAttribute("pageInfo", pageInfo);
        return "cargo/invoice/invoice-list";
    }

    @RequestMapping("/toAdd")
    public String toAdd(String id) {
        Shipping shipping = shippingService.findById(id);
        Packing packing = packingService.findById(id);
        Invoice invoice = new Invoice();

        Double invoiceMoney = 0d;
        String trandTerms = "";
        invoiceMoney += shipping.getShippingMoney();
        invoiceMoney += packing.getPackingMoney();
        ExportExample exportExample = new ExportExample();
        exportExample.createCriteria().andIdIn(Arrays.asList(packing.getExportIds().split(",")));
        List<Export> exportList = exportService.findByIds(exportExample);
        if (exportList != null && exportList.size() > 0) {
            for (Export export : exportList) {
                ContractExample contractExample = new ContractExample();
                contractExample.createCriteria().andIdIn(Arrays.asList(export.getContractIds().split(",")));
                List<Contract> contractList = contractService.findAll(contractExample);
                if (contractList != null && contractList.size() > 0) {
                    for (Contract contract : contractList) {
                        if (contract.getTotalAmount() != null) {
                            invoiceMoney += contract.getTotalAmount();
                        }
                        if (contract.getTradeTerms() != null) {
                            trandTerms += contract.getTradeTerms() + " ";
                        }
                    }
                }
            }
        }

    //计算发票金额
    invoice.setInvoiceId(id);
    invoice.setTrandTerms(trandTerms);
    invoice.setInvoiceMoney(invoiceMoney);
    invoice.setScNo(packing.getExportNos());
    request.setAttribute("invoice", invoice);
        return "cargo/invoice/invoice-toShip";
    }

    //  删除
    @RequestMapping("/delete")
    @ResponseBody
    public Map<String, Object> delete(String id) {
        //Invoice invoice = invoiceService.findById(id);
        //if (invoice.getStatus() != 2) {

        //}
        return invoiceService.delete(id);
    }

    //  保存
    @RequestMapping("/save")
    public String save(Invoice invoice, MultipartFile file) {
        invoice.setCompanyId(getLoginCompanyId());
        invoice.setCompanyName(getLoginCompanyName());
        invoice.setCreateBy(getLoginUser().getId());
        invoice.setCreateDept(getLoginUser().getDeptId());
        if (file != null) {
            try {
                // 上传文件，获取上传文件的完整路径
                String url = "http://" + fileUploadUtil.upload(file);
                // 保存上传的图片路径
                invoice.setPickupPhoto(url);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        invoiceService.save(invoice);
        return "redirect:/cargo/invoice/list";

    }

    @RequestMapping("/toExcel")
    @ResponseBody
    public void toExcel(String id) throws Exception {
        Invoice invoice = invoiceService.findById(id);
        Shipping shipping = shippingService.findById(id);
        Packing packing = packingService.findById(id);
        InputStream in = session.getServletContext().getResourceAsStream("/make/xlsprint/tSHIPPINGORDER.xls");
        Workbook workbook = new HSSFWorkbook(in);
        Sheet sheet = workbook.getSheetAt(0);

        Row row = sheet.getRow(3);
        Cell cell = row.getCell(0);
        cell.setCellValue(shipping.getShipper());
        cell = row.getCell(2);
        cell.setCellValue("黑马商务发展有限公司");
        row = sheet.getRow(5);
        cell = row.getCell(5);
        cell.setCellValue("T E L:0230082");
        cell = row.getCell(7);
        cell.setCellValue("F A X:02302280");
        row = sheet.getRow(8);
        cell = row.getCell(0);
        cell.setCellValue(shipping.getConsignee());
        row = sheet.getRow(15);
        cell = row.getCell(0);
        cell.setCellValue(shipping.getNotifyPariy());
        row = sheet.getRow(19);
        cell = row.getCell(1);
        cell.setCellValue(id);
        cell = row.getCell(3);
        cell.setCellValue(new Date());
        cell = row.getCell(6);
        cell.setCellValue(shipping.getLcNo());
        row = sheet.getRow(23);
        cell = row.getCell(0);
        cell.setCellValue(invoice.getInvoiceMoney());
 /*        cell = row.getCell(3);
        cell.setCellValue(shipping.getPortOfTrans() != null? shipping.getPortOfTrans() : "");
        cell = row.getCell(6);
        cell.setCellValue(shipping.getPortOfDischar());
        row = sheet.getRow(27);
        cell = row.getCell(0);
        cell.setCellValue(shipping.getLoadingDate());
        cell = row.getCell(2);
        cell.setCellValue(shipping.getLimitDate());
        cell = row.getCell(3);
        cell.setCellValue(shipping.getIsBatch().equals("1")?"是":"否");
        cell = row.getCell(5);
        cell.setCellValue(shipping.getIsTrans().equals("1")?"是":"否");
        cell = row.getCell(7);
        cell.setCellValue(shipping.getCopyNum() != null? shipping.getCopyNum():"");
        row = sheet.getRow(31);
        cell = row.getCell(0);
        cell.setCellValue(shipping.getMarks() + packing.getExportNos());
        cell = row.getCell(1);
        cell.setCellValue(packing.getDescription()!=null?packing.getDescription():"");
        cell = row.getCell(3);
        cell.setCellValue(packing.getNetWeights() + "CTNS");
        cell = row.getCell(4);
        cell.setCellValue(packing.getGrossWeights() + "KGS");
        cell = row.getCell(6);
        cell.setCellValue(packing.getTotalVolume() + "M3");
        row = sheet.getRow(37);
        cell = row.getCell(1);
        cell.setCellValue(shipping.getSpecialConditio()!=null?shipping.getSpecialConditio():"");*/
        response.setHeader("content-disposition", "attachment;filename=shippingOrder.xls");
        ServletOutputStream outputStream = response.getOutputStream();
        workbook.write(outputStream);
        outputStream.close();
        workbook.close();
    }

}